package cn.com.ejiakanghu.service;


import cn.com.ejiakanghu.core.utils.ApplicationContextRegister;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * 缓存系统中的验证码
 */
public class CaptchaCodeManager {

    /**
     * 添加到缓存
     *
     * @param phoneNumber 电话号码
     * @param code        验证码
     */
    public static boolean addToCache(String phoneNumber, String code, long timeout) {
        StringRedisTemplate redisTemplate = ApplicationContextRegister.getBean(StringRedisTemplate.class);
        String key = "wl-" + phoneNumber;
        String codeStr = redisTemplate.opsForValue().get(key);
        if(StringUtils.isNotBlank(codeStr)) {
            redisTemplate.delete(key);
        }
        redisTemplate.opsForValue().set(key, code);
        redisTemplate.expire(key, timeout, TimeUnit.MINUTES);
        return true;
    }

    /**
     * 获取缓存的验证码
     *
     * @param phoneNumber 关联的电话号码
     * @return 验证码
     */
    public static String getCachedCaptcha(String phoneNumber) {
        StringRedisTemplate redisTemplate = ApplicationContextRegister.getBean(StringRedisTemplate.class);
        String key = "wl-" + phoneNumber;
        String codeStr = redisTemplate.opsForValue().get(key);
        return codeStr;
    }
}
